package edu.uoc.tfc.web.tags;

import java.lang.reflect.Method;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.config.ActionConfig;

import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.model.JSONValue;

public class JSONTag extends EmktBaseTag {

    private static final long serialVersionUID = 1L;

	private static final Logger LOG = Logger.getLogger(JSONTag.class);
	
    private PageContext pageContext;

    /**
     * Returns pageContext.
     *
     * @return pageContext
     */
    public PageContext getPageContext() {
        return this.pageContext;
    }

    /**
     * Setear el contexto de la pagina.
     *
     * @param pageContext el contexto de la pagina.
     * @see javax.servlet.jsp.tagext.Tag#setPageContext(javax.servlet.jsp.PageContext)
     */
    public void setPageContext(PageContext pageContext) {
        this.pageContext = pageContext;
    }


	@Override
	public int doStartTag() throws JspException {
		

        try {
        	ActionConfig actionInstance =
                    (ActionConfig) this.getPageContext().
                    	getRequest().getAttribute("org.apache.struts.action.mapping.instance");
    		
    		
        	ActionForm formBean = 
        			(ActionForm) this.getPageContext().
        				getRequest().getAttribute(actionInstance.getName());
        	
    		Object objeto = this.parseaObjeto(formBean);
    		JSONValue jsonValue = JSONMapper.toJSON(objeto);

            
            JspWriter out = this.getPageContext().getOut();
            this.getPageContext().getResponse().setContentType("application/json");
			//out.write(xstream.toXML(objeto));
            out.write(jsonValue.render(true));
			
		} catch (Exception e) {
			LOG.error("Error parseando objeto a JSON: " + this.getProperty(), e);
			throw new JspException("Error parseando objeto a JSON: " + this.getProperty());
		} 

		
		return SKIP_BODY;
	}
	
    private Object parseaObjeto(ActionForm formBean)throws Exception {
    	
    	Method[] metodos = formBean.getClass().getMethods();
    	Method getter = null;
    	
    	for (int i = 0; i < metodos.length; i++) {
			if (metodos[i].getName().equalsIgnoreCase("get" + this.getProperty())) {
				getter = metodos[i];
			}
		}
    	
    	Object returnValue = getter.invoke(formBean, new Object[]{});
		return returnValue;
	}

	public int doEndTag() {
        return EVAL_PAGE;
    }

	
}
